/*!
    \file    usbh_printer_core.c
    \brief   USB host printer class driver

    \version 2020-08-01, V3.0.0, firmware for GD32F4xx
    \version 2022-03-09, V3.1.0, firmware for GD32F4xx
    \version 2022-06-30, V3.2.0, firmware for GD32F4xx
*/

/*
    Copyright (c) 2022, GigaDevice Semiconductor Inc.

    Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this 
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice, 
       this list of conditions and the following disclaimer in the documentation 
       and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors 
       may be used to endorse or promote products derived from this software without 
       specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY 
OF SUCH DAMAGE.
*/

#include <string.h>
#include <stdbool.h>
#include "usbh_pipe.h"
#include "usbh_printer_core.h"
#include "usbh_standard_printer.h"

/* local function prototypes ('static') */
static void usbh_printerdesc_parse (usb_desc_printer *printer_desc, uint8_t *buf);
static void usbh_printer_itf_deinit (usbh_host *uhost);
static usbh_status usbh_printer_itf_init (usbh_host *uhost);
static usbh_status usbh_printer_class_req (usbh_host *uhost);
static usbh_status usbh_printer_handle (usbh_host *uhost);
static usbh_status usbh_printer_reportdesc_get (usbh_host *uhost, uint16_t len);
static usbh_status usbh_printer_sof(usbh_host *uhost);
static usbh_status usbh_printer_desc_get (usbh_host *uhost, uint16_t len);
static usbh_status usbh_set_idle (usbh_host *uhost, uint8_t duration, uint8_t report_ID);
static usbh_status usbh_set_protocol (usbh_host *uhost, uint8_t protocol);

usbh_class usbh_printer = 
{
    USB_PRINTER_CLASS,
    usbh_printer_itf_init,
    usbh_printer_itf_deinit,
    usbh_printer_class_req,
    usbh_printer_handle,
    usbh_printer_sof
};

/*!
    \brief      get report
    \param[in]  uhost: pointer to USB host
    \param[in]  report_type: duration for PRINTER set idle request
    \param[in]  report_ID: targeted report ID for PRINTER set idle request
    \param[in]  report_len: length of data report to be send
    \param[in]  report_buf: report buffer
    \param[out] none
    \retval     operation status
*/
usbh_status usbh_get_report (usbh_host *uhost,
                             uint8_t  report_type,
                             uint8_t  report_ID,
                             uint8_t  report_len,
                             uint8_t *report_buf)
{
    usbh_status status = USBH_BUSY;

    if (CTL_IDLE == uhost->control.ctl_state) {
        uhost->control.setup.req = (usb_req) {
            .bmRequestType = USB_TRX_IN | USB_RECPTYPE_ITF | USB_REQTYPE_CLASS,
            .bRequest      = GET_REPORT,
            .wValue        = (report_type << 8U) | report_ID,
            .wIndex        = 0U,
            .wLength       = report_len
        };

        usbh_ctlstate_config (uhost, report_buf, report_len);
    }

    status = usbh_ctl_handler (uhost);

    return status;
}

/*!
    \brief      set report
    \param[in]  udev: pointer to USB core instance
    \param[in]  uhost: pointer to USB host
    \param[in]  report_type: duration for PRINTER set idle request
    \param[in]  report_ID: targeted report ID for PRINTER set idle request
    \param[in]  report_len: length of data report to be send
    \param[in]  report_buf: report buffer
    \param[out] none
    \retval     operation status
*/
usbh_status usbh_set_report (usb_core_driver *udev, 
                             usbh_host *uhost,
                             uint8_t  report_type,
                             uint8_t  report_ID,
                             uint8_t  report_len,
                             uint8_t *report_buf)
{
    usbh_status status = USBH_BUSY;

    if (CTL_IDLE == uhost->control.ctl_state) {
        uhost->control.setup.req = (usb_req) {
            .bmRequestType = USB_TRX_OUT | USB_RECPTYPE_ITF | USB_REQTYPE_CLASS,
            .bRequest      = SET_REPORT,
            .wValue        = (report_type << 8U) | report_ID,
            .wIndex        = 0U,
            .wLength       = report_len
        };

        usbh_ctlstate_config (uhost, report_buf, report_len);
    }

    status = usbh_ctl_handler (uhost);

    return status;
}

/*!
    \brief      deinitialize the host pipes used for the PRINTER class
    \param[in]  uhost: pointer to USB host
    \param[out] none
    \retval     operation status
*/
void usbh_printer_itf_deinit (usbh_host *uhost)
{
    usbh_printer_handler *printer = (usbh_printer_handler *)uhost->active_class->class_data;

    if (0x00U != printer->pipe_in) {
        usb_pipe_halt (uhost->data, printer->pipe_in);

        usbh_pipe_free (uhost->data, printer->pipe_in);

        printer->pipe_in = 0U;     /* reset the pipe as free */
    }

    if (0x00U != printer->pipe_out) {
        usb_pipe_halt (uhost->data, printer->pipe_out);

        usbh_pipe_free (uhost->data, printer->pipe_out);

        printer->pipe_out = 0U; /* reset the channel as free */
    }
}

/*!
    \brief      return device type
    \param[in]  udev: pointer to USB core instance
    \param[in]  uhost: pointer to USB host
    \param[out] none
    \retval     printer_type
*/
printer_type usbh_printer_device_type_get(usb_core_driver *udev, usbh_host *uhost)
{
    printer_type type = PRINTER_UNKNOWN;
    uint8_t interface_protocol;

    if (HOST_CLASS_HANDLER == uhost->cur_state) {
        interface_protocol = uhost->dev_prop.cfg_desc_set.itf_desc_set[uhost->dev_prop.cur_itf][0].itf_desc.bInterfaceProtocol;

        if (USB_PRINTER_PROTOCOL_KEYBOARD == interface_protocol) {
            type = PRINTER_KEYBOARD;
        } else {
            if (USB_PRINTER_PROTOCOL_MOUSE == interface_protocol) {
                type = PRINTER_MOUSE;
            }
        }
    }

    return type;
}

/*!
    \brief      return PRINTER device poll time
    \param[in]  udev: pointer to USB core instance
    \param[in]  uhost: pointer to USB host
    \param[out] none
    \retval     poll time (ms)
*/
uint8_t usbh_printer_poll_interval_get (usb_core_driver *udev, usbh_host *uhost)
{
    usbh_printer_handler *printer = (usbh_printer_handler *)uhost->active_class->class_data;

    if ((HOST_CLASS_ENUM == uhost->cur_state) ||
         (HOST_USER_INPUT == uhost->cur_state) ||
           (HOST_CLASS_CHECK == uhost->cur_state) ||
             (HOST_CLASS_HANDLER == uhost->cur_state)) {
        return (uint8_t)(printer->poll);
    } else {
        return 0U;
    }
}

/*!
    \brief      initialize the printer class
    \param[in]  uhost: pointer to USB host
    \param[out] none
    \retval     operation status
*/
static usbh_status usbh_printer_itf_init (usbh_host *uhost)
{
    uint8_t num = 0U, ep_num = 0U, interface = 0U;
    usbh_status status = USBH_BUSY;

    interface = usbh_interface_find(&uhost->dev_prop, USB_PRINTER_CLASS, USB_PRINTER_SUBCLASS_BOOT_ITF, 0xFFU);

    if (0xFFU == interface) {
        uhost->usr_cb->dev_not_supported();

        status = USBH_FAIL;
    } else {
        usbh_interface_select(&uhost->dev_prop, interface);

        static usbh_printer_handler printer_handler;

        memset((void*)&printer_handler, 0, sizeof(usbh_printer_handler));

        printer_handler.state = PRINTER_ERROR;

        uint8_t itf_protocol = uhost->dev_prop.cfg_desc_set.itf_desc_set[uhost->dev_prop.cur_itf][0].itf_desc.bInterfaceProtocol;
        if (USB_PRINTER_PROTOCOL_KEYBOARD == itf_protocol) {
            printer_handler.init = usbh_printer_keybrd_init;
            printer_handler.decode = usbh_printer_keybrd_decode;
        } else if (USB_PRINTER_PROTOCOL_MOUSE == itf_protocol) {
            printer_handler.init = usbh_printer_mouse_init;
            printer_handler.decode = usbh_printer_mouse_decode;
        } else {
            status = USBH_FAIL;
        }

        printer_handler.state = PRINTER_INIT;
        printer_handler.ctl_state = PRINTER_REQ_INIT;
        printer_handler.ep_addr = uhost->dev_prop.cfg_desc_set.itf_desc_set[uhost->dev_prop.cur_itf][0].ep_desc[0].bEndpointAddress;
        printer_handler.len = uhost->dev_prop.cfg_desc_set.itf_desc_set[uhost->dev_prop.cur_itf][0].ep_desc[0].wMaxPacketSize;
        printer_handler.poll = uhost->dev_prop.cfg_desc_set.itf_desc_set[uhost->dev_prop.cur_itf][0].ep_desc[0].bInterval;

        if (printer_handler.poll < PRINTER_MIN_POLL) {
            printer_handler.poll = PRINTER_MIN_POLL;
        }

        /* check for available number of endpoints */
        /* find the number of endpoints in the interface descriptor */
        /* choose the lower number in order not to overrun the buffer allocated */
        ep_num = USB_MIN(uhost->dev_prop.cfg_desc_set.itf_desc_set[uhost->dev_prop.cur_itf][0].itf_desc.bNumEndpoints, USBH_MAX_EP_NUM);

        /* decode endpoint IN and OUT address from interface descriptor */
        for (num = 0U; num < ep_num; num++) {
            usb_desc_ep *ep_desc = &uhost->dev_prop.cfg_desc_set.itf_desc_set[uhost->dev_prop.cur_itf][0].ep_desc[num];

            uint8_t ep_addr = ep_desc->bEndpointAddress;

            if (ep_addr & 0x80U) {
                printer_handler.ep_in = ep_addr;
                printer_handler.pipe_in = usbh_pipe_allocate (uhost->data, ep_addr);

                /* open channel for IN endpoint */
                usbh_pipe_create (uhost->data,
                                  &uhost->dev_prop, 
                                  printer_handler.pipe_in,
                                  USB_EPTYPE_INTR,
                                  printer_handler.len);

                usbh_pipe_toggle_set(uhost->data, printer_handler.pipe_in, 0U);
            } else {
                printer_handler.ep_out = ep_addr;
                printer_handler.pipe_out = usbh_pipe_allocate (uhost->data, ep_addr);

                /* open channel for OUT endpoint */
                usbh_pipe_create (uhost->data,
                                  &uhost->dev_prop,
                                  printer_handler.pipe_out,
                                  USB_EPTYPE_INTR,
                                  printer_handler.len);

                usbh_pipe_toggle_set(uhost->data, printer_handler.pipe_out, 0U);
            }
        }

        uhost->active_class->class_data = (void *)&printer_handler;

        status = USBH_OK;
    }

    return status;
}

/*!
    \brief      handle PRINTER class requests for PRINTER class
    \param[in]  uhost: pointer to USB host
    \param[out] none
    \retval     operation status
*/
static usbh_status usbh_printer_class_req (usbh_host *uhost)
{
    usbh_status status = USBH_BUSY;
    usbh_status class_req_status = USBH_BUSY;

    usbh_printer_handler *printer = (usbh_printer_handler *)uhost->active_class->class_data;

    /* handle PRINTER control state machine */
    switch (printer->ctl_state) {
    case PRINTER_REQ_INIT:
    case PRINTER_REQ_GET_PRINTER_DESC:
        /* get PRINTER descriptor */ 
        if (USBH_OK == usbh_printer_desc_get (uhost, USB_PRINTER_DESC_SIZE)) {
            usbh_printerdesc_parse(&printer->printer_desc, uhost->dev_prop.data);

            printer->ctl_state = PRINTER_REQ_GET_REPORT_DESC;
        }
        break;

    case PRINTER_REQ_GET_REPORT_DESC:
        /* get report descriptor */ 
        if (USBH_OK == usbh_printer_reportdesc_get(uhost, printer->printer_desc.wDescriptorLength)) {
            printer->ctl_state = PRINTER_REQ_SET_IDLE;
        }
        break;

    case PRINTER_REQ_SET_IDLE:
        class_req_status = usbh_set_idle (uhost, 0U, 0U);

        /* set idle */
        if (USBH_OK == class_req_status) {
            printer->ctl_state = PRINTER_REQ_SET_PROTOCOL;
        } else {
            if(USBH_NOT_SUPPORTED == class_req_status) {
                printer->ctl_state = PRINTER_REQ_SET_PROTOCOL;
            }
        }
        break; 

    case PRINTER_REQ_SET_PROTOCOL:
        /* set protocol */
        if (USBH_OK == usbh_set_protocol (uhost, 0U)) {
            printer->ctl_state = PRINTER_REQ_IDLE;

            /* all requests performed */
            status = USBH_OK;
        }
        break;

    case PRINTER_REQ_IDLE:
    default:
        break;
    }

    return status;
}

/*!
    \brief      manage state machine for PRINTER data transfers
    \param[in]  uhost: pointer to USB host
    \param[out] none
    \retval     operation status
*/
static usbh_status usbh_printer_handle (usbh_host *uhost)
{
    usbh_status status = USBH_OK;
    usbh_printer_handler *printer = (usbh_printer_handler *)uhost->active_class->class_data;

    switch (printer->state) {
    case PRINTER_INIT:
        printer->init(uhost->data, uhost);
        printer->state = PRINTER_IDLE;
        break;

    case PRINTER_IDLE:
        printer->state = PRINTER_SYNC;
        status = USBH_OK;
        break;

    case PRINTER_SYNC:
        /* sync with start of even frame */
        if (true == usb_frame_even(uhost->data)) {
            printer->state = PRINTER_GET_DATA;
        }
        break;

    case PRINTER_GET_DATA:
        usbh_data_recev (uhost->data, printer->pdata, printer->pipe_in, printer->len);

        printer->state = PRINTER_POLL;
        printer->timer = usb_curframe_get (uhost->data);
        printer->data_ready = 0U;
        break;

    case PRINTER_POLL:
        if (URB_DONE == usbh_urbstate_get (uhost->data, printer->pipe_in)) {
            if (0U == printer->data_ready) {
                printer->data_ready = 1U;

                printer->decode(printer->pdata);
            }
        } else {
            /* check IN endpoint stall status */
            if (URB_STALL == usbh_urbstate_get (uhost->data, printer->pipe_in)) {
                /* issue clear feature on interrupt in endpoint */ 
                if (USBH_OK == (usbh_clrfeature (uhost, printer->ep_addr, printer->pipe_in))) {
                    /* change state to issue next in token */
                    printer->state = PRINTER_GET_DATA;
                }
            }
        }
        break;

    default:
        break;
    }
    return status;
}

/*!
    \brief      send get report descriptor command to the device
    \param[in]  uhost: pointer to USB host
    \param[in]  len: PRINTER report descriptor length
    \param[out] none
    \retval     operation status
*/
static usbh_status usbh_printer_reportdesc_get (usbh_host *uhost, uint16_t len)
{
    usbh_status status = USBH_BUSY;

    if (CTL_IDLE == uhost->control.ctl_state) {
        uhost->control.setup.req = (usb_req) {
            .bmRequestType = USB_TRX_IN | USB_RECPTYPE_ITF | USB_REQTYPE_STRD,
            .bRequest      = USB_GET_DESCRIPTOR,
            .wValue        = USBH_DESC(USB_DESCTYPE_REPORT),
            .wIndex        = 0U,
            .wLength       = len
        };

        usbh_ctlstate_config (uhost, uhost->dev_prop.data, len);
    }

    status = usbh_ctl_handler (uhost);

    return status;
}

/*!
    \brief      managing the SOF process
    \param[in]  uhost: pointer to USB host
    \param[out] none
    \retval     operation status
*/
static usbh_status usbh_printer_sof(usbh_host *uhost)
{
    usbh_printer_handler *printer = (usbh_printer_handler *)uhost->active_class->class_data;

    if (PRINTER_POLL == printer->state) {
        uint32_t frame_count = usb_curframe_get (uhost->data);

        if ((frame_count > printer->timer) && ((frame_count - printer->timer) >= printer->poll)) {
            printer->state = PRINTER_GET_DATA;
        } else if ((frame_count < printer->timer) && ((frame_count + 0x3FFFU - printer->timer) >= printer->poll)) {
            printer->state = PRINTER_GET_DATA;
        } else {
            /* no operation */
        }
    }

    return USBH_OK;
}

/*!
    \brief      send the command of get PRINTER descriptor to the device
    \param[in]  uhost: pointer to USB host
    \param[in]  len: PRINTER descriptor length
    \param[out] none
    \retval     operation status
*/
static usbh_status usbh_printer_desc_get (usbh_host *uhost, uint16_t len)
{
    usbh_status status = USBH_BUSY;

    if (CTL_IDLE == uhost->control.ctl_state) {
        uhost->control.setup.req = (usb_req) {
            .bmRequestType = USB_TRX_IN | USB_RECPTYPE_ITF | USB_REQTYPE_STRD,
            .bRequest      = USB_GET_DESCRIPTOR,
            .wValue        = USBH_DESC(USB_DESCTYPE_PRINTER),
            .wIndex        = 0U,
            .wLength       = len
        };

        usbh_ctlstate_config (uhost, uhost->dev_prop.data, len);
    }

    status = usbh_ctl_handler (uhost);

    return status;
}

/*!
    \brief      set idle state
    \param[in]  uhost: pointer to USB host
    \param[in]  duration: duration for PRINTER set idle request
    \param[in]  report_ID: targeted report ID for PRINTER set idle request
    \param[out] none
    \retval     operation status
*/
static usbh_status usbh_set_idle (usbh_host *uhost, uint8_t duration, uint8_t report_ID)
{
    usbh_status status = USBH_BUSY;

    if (CTL_IDLE == uhost->control.ctl_state) {
        uhost->control.setup.req = (usb_req) {
            .bmRequestType = USB_TRX_OUT | USB_RECPTYPE_ITF | USB_REQTYPE_CLASS,
            .bRequest      = SET_IDLE,
            .wValue        = (duration << 8U) | report_ID,
            .wIndex        = 0U,
            .wLength       = 0U
        };

        usbh_ctlstate_config (uhost, NULL, 0U);
    }

    status = usbh_ctl_handler (uhost);

    return status;
}

/*!
    \brief      set protocol state
    \param[in]  uhost: pointer to USB host
    \param[in]  protocol: boot/report protocol
    \param[out] none
    \retval     operation status
*/
static usbh_status usbh_set_protocol (usbh_host *uhost, uint8_t protocol)
{
    usbh_status status = USBH_BUSY;

    if (CTL_IDLE == uhost->control.ctl_state) {
        uhost->control.setup.req = (usb_req) {
            .bmRequestType = USB_TRX_OUT | USB_RECPTYPE_ITF | USB_REQTYPE_CLASS,
            .bRequest      = SET_PROTOCOL,
            .wValue        = !protocol,
            .wIndex        = 0U,
            .wLength       = 0U
        };

        usbh_ctlstate_config (uhost, NULL, 0U);
    }

    status = usbh_ctl_handler (uhost);

    return status;
}

/*!
    \brief      parse the PRINTER descriptor
    \param[in]  printer_desc: pointer to PRINTER descriptor
    \param[in]  buf: pointer to buffer where the source descriptor is available
    \param[out] none
    \retval     none
*/
static void usbh_printerdesc_parse (usb_desc_printer *printer_desc, uint8_t *buf)
{
    printer_desc->header.bLength         = *(uint8_t *)(buf + 0U);
    printer_desc->header.bDescriptorType = *(uint8_t *)(buf + 1U);
    printer_desc->bcdPRINTER                 = BYTE_SWAP(buf + 2U);
    printer_desc->bCountryCode           = *(uint8_t *)(buf + 4U);
    printer_desc->bNumDescriptors        = *(uint8_t *)(buf + 5U);
    printer_desc->bDescriptorType        = *(uint8_t *)(buf + 6U);
    printer_desc->wDescriptorLength      = BYTE_SWAP(buf + 7U);
}
